import {clearUp} from './ws_util.js';

//是否已经连接上ws
let isOpenSocket = false
//心跳间隔，单位毫秒
let heartBeatDelay = 3000
let heartBeatInterval = null
//心跳时发送的消息文本
let heartBeatText = "{ping:PING}"
//最大重连次数
let reconnectTimes = 10
let reconnectInterval = null
//重连间隔，单位毫秒
let reconnectDelay = 3000

// 栈
let arrPath = []

let wsUrl = "wss://wjlm.goldsu.cn/websocket"

var socketTask = null

//这个参数是防止重连失败之后onClose方法会重复执行reconnect方法，导致重连定时器出问题
//连接并打开之后可重连，且只执行重连方法一次
let canReconnect = false

//封装的对象，最后以模块化向外暴露，
//init方法 初始化socketTask对象
//completeClose方法 完全将socketTask关闭（不重连）
//其他关于socketTask的方法与uniapp的socketTask api一致
let ws = {
	init,
	completeClose,
	socketTask:null,
	send
}

function init(data) {
	if (socketTask) {
		socketTask.close()
		arrPath = []
		socketTask = null	
		// uni.$off('onMessage')
	}

	socketTask = uni.connectSocket({
		url: wsUrl,
		data() {},
		complete: (res) => {
			console.log('创建', res)
		}
	})

	socketTask.onOpen((res) => {
		console.log("ws连接成功", res)
		let game_id = uni.getStorageSync("gameId")
		// succeed()
		let userData = uni.getStorageSync("userData")
		send(JSON.stringify({
			game_id,
			user_id: userData.id
		}))


		uni.hideLoading();
		clearInterval(heartBeatInterval)
		clearInterval(reconnectInterval)
		isOpenSocket = true
		canReconnect = true
		//开启心跳机制
		heartBeat()
	})


	socketTask.onClose((err) => {
		if (isOpenSocket) {
			console.log("ws与服务器断开")
		} else {
			console.log("连接失败",err)
		}
		// return;
		isOpenSocket = false
		if (canReconnect) {
			reconnect()
			canReconnect = false
		}
	})
	let time = null
	socketTask.onMessage(res=>{
		if (time !== null) {
			clearTimeout(time);
			time = null
		}
		time=setTimeout(()=>{
			clearUp(res).then(data=>{
				uni.$emit('onMessage', data) 
			})
			time = null
		},200)
		
	})

	ws.socketTask = socketTask
}

// function onMessage2(fn, path) {
// 	if (true) {	
// 		arrPath.push(path)
// 		let game_id = uni.getStorageSync("gameId")
// 		let userData = uni.getStorageSync("userData")
// 		let time = null
// 		send(JSON.stringify({
// 			game_id,
// 			user_id: userData.id
// 		}))
// 		// socketTask.
// 		onMessage((res) => {

// 			if (time !== null) {
// 				clearTimeout(time);
// 			}
// 			time = setTimeout(() => {
				
// 				let page = getCurrentPages();
// 				let currentRoute = page[page.length - 1].route
				
// 				if (path != currentRoute && path) return;
				
// 				//自定义处理onMessage方法
// 				let data_ = JSON.parse(res.data)
// 				let data = data_.data
// 				// console.log('返回数据',data)
// 				let userData = uni.getStorageSync("userData")
// 				if (data.team) {
// 					data.team.forEach(el => {
// 						el.people.forEach(els => {
// 							if (userData.id == els.user_id) {
// 								data.userPeople = els
// 								data.userPeople.teamId = el.id
// 								data.userPeople.cap_zt = els.cap_zt
// 							}
// 						})
// 						if (data.game_chall) {
// 							data.game_chall.forEach(item => {
// 								if (item.team_id == el.id) {
// 									item.teamList = el
// 									if (data.userPeople && data.userPeople.teamId == item.team_id &&
// 										data.userPeople.cap_zt == 2) data.userPeople.power = true
				
// 								}
// 							})	
// 						}
// 					})
// 				}
				
// 				//是否准备
// 				if (data.game_chall) {
// 					data.game_chall.forEach(item => {
// 						if (data.userPeople.teamId == item.team_id) {
// 							data.userPeople.status = item.status
// 						}
// 					})
// 				}
				
				
// 				let url = ''
// 				if (data.code == 201) {
// 					url = 'pages/createActivity/formTeam'
// 				} else if (data.code == 202) {
// 					console.log('waht?????',data.game_config)
// 					if (data.game_config.status == 1) {
// 						if(data.game_config.type==11||data.game_config.type==12){
						
// 							url = 'pages/gameTemplate/bingo/bingo'
// 						}else{
// 							url = 'pages/createActivity/clapSetout'
// 						}
// 					} else if (data.game_config.type == 9 || data.game_config.type == 10) {
// 						if (data.game_config.game_status == 1) {
// 							url = 'pages/gameTemplate/A11'
// 						} else if (data.game_config.game_status == 2 || data.game_config.game_status == 3 || data
// 							.game_config.game_status == 4) {
// 							url = 'pages/gameTemplate/A12'
// 						}
						
				
				
// 					} else if (data.game_config.status == 2 || data.game_config.game_status) {
				
// 						if (data.game_config.game_status == 0 && data.game_config.type == 7) {
// 							url = 'pages/gameTemplate/A8'
// 						} else if (data.game_config.game_status == 0 && (data.game_config.type == 8 || data
// 								.game_config.type == 10)) {
// 							url = 'pages/gameTemplate/A8'
// 						} else if (data.game_chall[0].time == 0) {
// 							url = 'pages/gameTemplate/timekeeping/timekeeping'
// 							if (data.game_config.type == 7) url = 'pages/gameTemplate/relayGame/relayGame'
// 						} else {
// 							switch (data.game_config.type) {
// 								case 1:
// 									url = 'pages/gameTemplate/timekeeping/timekeeping'
// 									break;
// 								case 2:
// 									url = 'pages/gameTemplate/timekeeping/timekeeping'
// 									break;
// 								case 3:
// 									url = 'pages/gameTemplate/A9'
// 									break;
// 								case 4:
// 									url = 'pages/gameTemplate/A9'
// 									break;
// 								case 5:
// 									url = 'pages/gameTemplate/A9'
// 									break;
// 								case 6:
// 									url = 'pages/gameTemplate/A9'
// 									break;
// 								case 7:
// 									url = 'pages/gameTemplate/relayGame/relayGame'
// 									break;
// 								case 8:
// 									url = 'pages/gameTemplate/A5'
// 									break;
// 								case 9:
// 									break;
// 								case 10:
// 									break;
				
// 								default:
// 									break;
// 							}
// 						}
				
// 					} else if (data.game_config.status == 3) {
// 						url = 'pages/gameTemplate/preliminarySummary'
// 					}
// 				} else if (data.code == 203) {
				
// 					url = 'pages/gameTemplate/teamRanking'
// 					// 'pages/gameTemplate/preliminarySummary'
				
// 				} else if (data.code == 204) {
// 					url = 'pages/gameTemplate/teamRanking'
// 				} else if (data.code == 205) {
// 					url = 'pages/createActivity/prepare'
// 				} else if (data.code == 206) {
				
// 					url = 'pages/gameTemplate/decodeing'
// 				} else {
				
// 					url = 'pages/gameTemplate/takeBreak'
// 				}
				
// 				//前台跳转 禁止后台覆盖
// 				if (currentRoute == 'pages/gameTemplate/A3' && url ==
// 					'pages/gameTemplate/timekeeping/timekeeping' && data.game_chall[0].time != 0) return fn(data_);
				
// 				if (currentRoute == 'pages/gameTemplate/teamRanking' && url ==
// 					'pages/gameTemplate/preliminarySummary') return fn(data_);
				
// 				if (currentRoute == 'pages/gameTemplate/decoration' && url == 'pages/createActivity/prepare')
// 				return fn(data_);
// 				if (url !== currentRoute && currentRoute != 'pages/gameTemplate/clue') {
				
// 					uni.redirectTo({
// 						url: `/${url}`,
// 						success() {
// 							fn(data_)
// 						}
// 					});
// 				}
// 				fn(data_)
// 				// fn(data)	

// 			}, 100)



// 		})

// 	}
// }

function heartBeat() {
	heartBeatInterval = setInterval(() => {
		send(JSON.stringify(heartBeatText));
	}, heartBeatDelay)
}

function send(value) {
	console.log('发送消息：', value)
	socketTask.send({
		data: value,
		async success() {
			console.log("消息发送成功")
		}
	});
}


function reconnect() {
	//停止发送心跳
	clearInterval(heartBeatInterval)
	//如果不是人为关闭的话，进行重连
	if (!isOpenSocket) {
		let count = 0;
		reconnectInterval = setInterval(() => {
			uni.showLoading({
				title: '正在尝试重连'
			});
			init();
			count++
			//重连一定次数后就不再重连
			if (count >= reconnectTimes) {
				clearInterval(reconnectInterval)
				uni.showToast({
					title: '网络异常或服务器错误',
					icon: 'none'
				});
			}
		}, reconnectDelay)
	}
}

function completeClose() {

	if (socketTask) {
		//先将心跳与重连的定时器清除
		clearInterval(heartBeatInterval)
		clearInterval(reconnectInterval)
		canReconnect = false
		console.log('尝试断开连接')
		socketTask.close()
		arrPath = []
		socketTask = null


	}
}

module.exports = ws
